<template>
  <el-dialog :model-value="dialogAdd" width="55%" :before-close="handleClose">
    <template #header>
      <h3 style="padding-bottom: 10px">选择用户</h3>
    </template>
    <!-- 表单 -->
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="用户名称">
        <el-input
          v-model="formInline.userName"
          placeholder="请输入用户名称"
          clearable
          style="width: 250px"
          v-noSpace
        />
      </el-form-item>
      <el-form-item label="手机号码">
        <el-input
          v-model="formInline.mobile"
          type="number"
          placeholder="请输入手机号码"
          clearable
          style="width: 250px"
          v-noSpace
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="Search">搜索</el-button>
        <el-button @click="Reset">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="page-content">
      <!-- 表格 -->
      <el-table
        ref="myTableRef"
        :data="tableData"
        border
        stripe
        fit
        empty-text="暂无数据"
        show-header
        v-loading="loading"
        size="default"
        element-loading-text="Loading..."
        :header-cell-style="{ background: '#e7e1fb' }"
        style="width: 100%"
        @select="handleSelectionChange"
        @select-all="handleSelectAll"
        max-height="400px"
      >
        <el-table-column type="selection" prop="roleId" width="55" />
        <el-table-column prop="userName" label="用户名称" />
        <el-table-column prop="mobile" label="手机" />
        <el-table-column prop="banned" label="状态" v-slot="scope">
          <span :style="scope.row.banned === 0 ? {} : { color: 'red' }">
            {{ scope.row.banned === 0 ? '正常' : '禁用' }}
          </span>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
      </el-table>
    </div>

    <template #footer>
      <!-- 分页器 -->
      <div class="Addpagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[20, 40, 80, 100]"
          background
          layout="total,sizes, prev, pager, next,jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { AssigningUsers, addAllotUser } from '@/api/permission/role';
import { onMounted, ref, computed } from 'vue';
import { useRoute } from 'vue-router';
const route = useRoute();
// 从路由参数中获取 roleId
const roleId = computed(() => route.params.id);
defineProps({
  dialogAdd: {
    type: Boolean,
  },
});
// 分页变量
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);

// 表单数据
const multipleSelection = ref([]);
const formInline = ref({
  userName: '',
  mobile: '',
});
// 列表数据+表单校验
const tableData = ref([]);
const loading = ref(true);
const myTableRef = ref(null);
// 分页逻辑
const handleSizeChange = async (val) => {
  pageSize.value = val;
  addAssigningUsersList();
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  addAssigningUsersList();
};
// 获取列表
const addAssigningUsersList = async () => {
  loading.value = true;
  const res = await AssigningUsers({
    ...formInline.value,
    roleId: roleId.value,
  });
  if (res.data.code === 200) {
    tableData.value = res.data.data;
    total.value = res.data.data.length || 0;
    loading.value = false;
  }
};
const hasSearchConditions = () => {
  const { userName, mobile } = formInline.value;
  return userName || mobile;
};
const Search = async () => {
  if (!hasSearchConditions()) {
    // eslint-disable-next-line no-undef
    ElMessage({
      message: '请至少输入一个搜索条件',
      type: 'warning',
    });
    return;
  }
  addAssigningUsersList();
};
// 重置
const Reset = () => {
  // 如果当前已经是空值状态，直接返回
  if (formInline.value.userName === '' && formInline.value.mobile === '') {
    return;
  }
  formInline.value = {};
  multipleSelection.value = [];
  myTableRef.value?.clearSelection();
  addAssigningUsersList();
};
// 全选
const handleSelectAll = (val) => {
  multipleSelection.value = val;
};
// 单选
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

// 定义 emits，向父组件发送事件
const emit = defineEmits(['confirm', 'cancel']);

// 定义响应式变量，控制对话框的显示和隐藏

// 处理取消按钮的点击事件
const handleCancel = () => {
  formInline.value = {};
  multipleSelection.value = [];
  myTableRef.value?.clearSelection();
  emit('cancel');
};

// 处理确认按钮的点击事件
const handleConfirm = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage({
      message: '请至少选择一个用户',
      type: 'warning',
    });
    return;
  }

  const res = await addAllotUser({
    roleId: roleId.value,
    allotUserIdList: multipleSelection.value.map((item) => item.userId),
  });
  if (res.data.code === 200) {
    ElMessage.success('添加成功');
    handleCancel();
    emit('confirm');
  } else {
    ElMessage.error(res.data.msg);
  }
};

// 关闭对话框
const handleClose = () => {
  handleCancel();
};
onMounted(() => {
  addAssigningUsersList();
});
</script>

<style scoped>
.Addpagination {
  display: flex;
  justify-content: center;
  align-items: center;

  margin: 20px 0px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

/* 可以添加一些选中状态的样式 */
:deep(.el-table .el-table__row.selected) {
  background-color: #f5f7fa;
}
</style>
